import { mergecart ,cartlist } from "@/utils/Api/NavText"
export default {
  namespaced: true,
  state: {
    list: [],
  },
  mutations: {
    //添加商品到购物车
    addlist(state, obj) {
      state.list.push(obj);
    },
    //修改数量 obj.index 下标  obj,number要修改的数量
    changenum(state, obj) {
      state.list[obj.index].count += obj.number
    },
    jia(state, index) {
      state.list[index].count++
    },
    jian(state, index) {
      state.list[index].count--
    },
    dels(state, index) {
      state.list.splice(index, 1)
    },
    quan(state, flag) {
      state.list.forEach(item => {
        item.selected = flag
        // console.log(item.selected);
        // console.log(flag);
      })
    },
    fan(state, index) {
      state.list[index].selected = !state.list[index].selected
    },
    alldel(state) {
      state.list = state.list.filter(item => {
        return !item.selected
      })
    },
    clearList(state) {
      state.list = []
    },
    setList(state, arr) {
      state.list = arr
    }
  },
  getters: {
    cartnum(state) {
      let sum = 0
      state.list.forEach(item => {
        sum += item.count
      });
      return sum
    },
    xuanlist(state) {
      let sum = 0
      state.list.forEach(item => {
        if (item.selected) {
          sum += item.count
        }

      });
      return sum
    },
    allprice(state) {
      let sum = 0
      state.list.forEach(item => {
        if (item.selected) {
          sum += item.count * item.price
        }
      })
      return sum
    },
    zongprice(state) {
      let sum = 0
      state.list.forEach(item => {
        sum += item.count * item.price
      })
      return sum
    },
    mergelist(state) {
      return state.list.map(item => {
        return {
          skuId: item.skuid,
          selected: item.selected,
          count: item.count
        }
      })
    }
  },
  actions: {
    async asyncmergelist(context) {
      await mergecart(context.getters.mergelist)
      context.commit('clearList')
    },
    async asynccartlist(context){
      let res = await cartlist()
      context.commit("setList",res.result)
    }
  }
};
